package com.xauto.pioneer.appuser.activity.mine;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.xauto.pioneer.appuser.R;
import com.xauto.pioneer.appuser.activity.BaseActivity;
import com.xauto.pioneer.appuser.adapter.VoucherAdapter;
import com.xauto.pioneer.appuser.http.BaseLHttpHandler;
import com.xauto.pioneer.appuser.http.Constants;
import com.xauto.pioneer.appuser.http.LHttpLib;
import com.xauto.pioneer.appuser.model.JSONStatus;
import com.xauto.pioneer.appuser.model.PageInfo;
import com.xauto.pioneer.appuser.model.VoucherDetailInfo;
import com.xauto.pioneer.appuser.view.PromptDialog;
import com.xauto.pioneer.appuser.view.TopBar;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/***
 * 优惠券列表 页面
 *
 * @author Lemon Thu 9 Mar 11:34
 */
public class VoucherListActivity extends BaseActivity {

    @Bind(R.id.unused_text)
    TextView unusedText;
    @Bind(R.id.used_text)
    TextView usedText;
    @Bind(R.id.mark_view)
    View markView;
    @Bind(R.id.operate_linear)
    LinearLayout operateLinear;
    @Bind(R.id.tvEnsure)
    TextView tvEnsure;
    private PromptDialog promptDialog;
    @Bind(R.id.topBar)
    TopBar topBar;
    @Bind(R.id.list)
    PullToRefreshListView pullToRefreshListView;
    private ListView list;
    private VoucherAdapter adapter;
    private List<VoucherDetailInfo> voucherDetailInfoList;
    private String currentType = "1";
    private String car_order_no = "";
    //是否来自于订单界面
    boolean isFromOrder;
    //当前点击的优惠券信息
    VoucherDetailInfo voucherDetailInfo;
    String Route="";
    String VouchID="";
    String VouchName="";
    int VouchPosition=0;
    View emptyView;
    /**
     *
     * @param context
     * @param isFromOrder
     */
    public static void startAction(Activity context, boolean isFromOrder, String car_order_no,int VouchPosition,String route){
        Intent intent = new Intent(context,VoucherListActivity.class);
        intent.putExtra("isFromOrder",isFromOrder);
        intent.putExtra("car_order_no",car_order_no);
        intent.putExtra("VouchPosition",VouchPosition);
        intent.putExtra("route",route);
        context.startActivityForResult(intent,1000);
    }
    @Override
    protected int getContentView() {
        return R.layout.ac_voulist_list;
    }

    @Override
    protected void initView() {
        topBar.showView(TopBar.LEFT_IMAGE_BTN, TopBar.TITLE);
        topBar.setImage(TopBar.LEFT_IMAGE_BTN, R.mipmap.ic_common_left);
        topBar.setText(TopBar.TITLE, R.string.mine_coupon);
        topBar.setLeftOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        promptDialog = new PromptDialog(mContext, getString(R.string.notice), getString(R.string.text_not_network),
                getString(R.string.to_setting), getString(R.string.logout),getString(R.string.dialogpic_notice), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //去设置
                promptDialog.dismiss();
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //退出
                promptDialog.dismiss();
            }
        });
        emptyView = LayoutInflater.from(mContext).inflate(R.layout.layout_listview_empty, null);
        ((TextView) emptyView.findViewById(R.id.tvEmptyNotice)).setText("当前无优惠券信息");
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        list = pullToRefreshListView.getRefreshableView();
        list.setVerticalScrollBarEnabled(false);
        list.setDividerHeight(3);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //当前点击优惠券
                voucherDetailInfo = adapter.getItem(position - 1);
                adapter.setSelectPosition(position-1);
                adapter.notifyDataSetChanged();
                VouchPosition=position - 1;
                Log.e("123",String.valueOf(VouchPosition));
                Intent intent1=new Intent();
                intent1.putExtra("voucherDetailInfo",voucherDetailInfo);
                intent1.putExtra("VouchPosition",VouchPosition);
                setResult(RESULT_OK,intent1);
                finish();

            }
        });
        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                //刷新
                page = 1;
                load();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                //下拉
                if (isMore){
                    page ++;
                    load();
                }else {
                    pullToRefreshListView.onRefreshComplete();
                    prompt("暂无更多数据");
                }
            }
        });
    }

    @Override
    protected void initData() {
        isFromOrder = getIntent().getBooleanExtra("isFromOrder",false);
        car_order_no = getIntent().getStringExtra("car_order_no");
        VouchPosition= getIntent().getIntExtra("VouchPosition",VouchPosition);
        Route=getIntent().getStringExtra("route");
        adapter = new VoucherAdapter(this, R.layout.item_voucher);
        adapter.setFromOrder(isFromOrder);
        list.setAdapter(adapter);
        if(VouchPosition!=101){
            voucherDetailInfo = adapter.getItem(VouchPosition);
            adapter.setSelectPosition(VouchPosition);
            adapter.notifyDataSetChanged();
        }
        page = 1;
        lHandler = new BaseLHttpHandler(mContext, true, true) {
            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                pullToRefreshListView.onRefreshComplete();
            }

            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                pullToRefreshListView.onRefreshComplete();
                JSONArray jsonArray = jsonStatus.data.optJSONArray("voucher_list");
                isMore = jsonStatus.pageInfo.more == 1 ? true : false;
                if (jsonArray != null && jsonArray.length() > 0) {
                    voucherDetailInfoList = new ArrayList<>();
                    for (int i = 0; i < jsonArray.length(); i++) {
                    voucherDetailInfoList.add(new VoucherDetailInfo().parse(jsonArray.optJSONObject(i)));
                    }
                    refreshList();
                } else {
                    if (page == 1)
                   showNoDataView();
                }
            }
        };
        if (isFromOrder){
            operateLinear.setVisibility(View.GONE);
            tvEnsure.setVisibility(View.VISIBLE);
        }
       //初始化数据
        load();
    }

    void refreshList() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (page == 1) {
                    adapter.getDataList().clear();
                }
                if(currentType=="1"){
                pullToRefreshListView.removeView(emptyView);
                markView.setVisibility("1".equals(currentType) ? View.GONE : View.VISIBLE);}
                adapter.getDataList().addAll(voucherDetailInfoList);
                adapter.notifyDataSetChanged();
                pullToRefreshListView.setAdapter(adapter);
            }
        });
    }

    private void showNoDataView() {
        adapter.getDataList().clear();
        adapter.notifyDataSetChanged();
        pullToRefreshListView.setEmptyView(emptyView);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    /**
     * 1-未使用/2-已使用/0-全部
     */
    void load() {
        new LHttpLib().getVoucherList(mContext, memberId, currentType, car_order_no, new PageInfo(page, Constants.COUNT), lHandler,Route);
    }

    @OnClick({R.id.unused_text, R.id.used_text,R.id.tvEnsure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.unused_text:
                unusedText.setBackgroundResource(R.drawable.bg_btn_white_shape);
                usedText.setBackgroundColor(getResources().getColor(R.color.transparent));
                currentType = "1";
                page = 1;
                adapter.setIs_used_tag(false);
                load();
                break;
            case R.id.used_text:
                usedText.setBackgroundResource(R.drawable.bg_btn_white_shape);
                unusedText.setBackgroundColor(getResources().getColor(R.color.transparent));
                currentType = "2";
                page = 1;
                adapter.setIs_used_tag(true);
                load();
                break;
            case R.id.tvEnsure:
                /*//选择优惠券之后的回调
                if (voucherDetailInfo == null){
                    prompt("请先选择一张优惠券");
                    return;
                }
                Intent intent1=new Intent();
                intent1.putExtra("voucherDetailInfo",voucherDetailInfo);
                intent1.putExtra("VouchPosition",VouchPosition);
                setResult(RESULT_OK,intent1);
                finish();*/
                Intent intent1=new Intent();
                intent1.putExtra("voucherDetailInfo",voucherDetailInfo);
                intent1.putExtra("VouchPosition",101);
                setResult(RESULT_OK,intent1);
                finish();
                break;
        }
    }
}
